//
//  LOSearchViewController.m
//  renmingongshe
//
//  Created by macbook on 2017/10/22.
//  Copyright © 2017年 xiaodian. All rights reserved.
//

#import "LOSearchViewController.h"
#import "selectLabelView.h"
#import "LOGoodsViewController.h"

@interface LOSearchViewController ()<UISearchBarDelegate>
@property (strong, nonatomic) UISearchBar *searchBar;
@property (strong, nonatomic) selectLabelView *labelView;
@property (strong, nonatomic) NSMutableArray *searchArr;
@property (strong, nonatomic) NSMutableArray *NetSearchArr;
@end

@implementation LOSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.titleLabel.text = @"搜索";
    _NetSearchArr = [NSMutableArray array];
    [self createSearchBar];
    [self createLabelView];
    if ([Utils getUserToken]) {
        [self downloadData];
    }else{
        _searchArr = [[NSMutableArray alloc] initWithArray:[Utils getSearchArr]];
        [_labelView reloadData:_searchArr];
    }
}

- (void)createSearchBar
{
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 80, WIDTH-20, 30)];
    _searchBar.backgroundColor = [UIColor clearColor];
    _searchBar.showsCancelButton = NO;
    _searchBar.delegate = self;
    _searchBar.placeholder = @"";
    
    for (UIView *subView in _searchBar.subviews) {
        if ([subView isKindOfClass:[UIView  class]]) {
            [[subView.subviews objectAtIndex:0] removeFromSuperview];
            if ([[subView.subviews objectAtIndex:0] isKindOfClass:[UITextField class]]) {
                UITextField *textField = [subView.subviews objectAtIndex:0];
                textField.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
                
                //设置默认文字颜色
                UIColor *color = [UIColor grayColor];
                [textField setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"搜索商品/店铺" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName:color}]];
                //修改默认的放大镜图片
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 13, 13)];
                imageView.backgroundColor = [UIColor clearColor];
                imageView.image = [UIImage imageNamed:@"LineDownSearch"];
                textField.leftView = imageView;
            }
        }
    }
    [self.view addSubview:_searchBar];
}

#pragma mark-seacherDelegate
//回车键或者键盘的return触发
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if ([Utils getUserToken]) {
        [THWManager PostHttp:API(LOGoodsList) Parameters:@{@"userToken":[Utils getUserToken],@"goodsName":_searchBar.text} Success:^(id responseObject) {
        } andFalse:^(NSError *error) {
        }];
    }else{
        if (_searchArr.count != 0) {
            if (![_searchArr containsObject:_searchBar.text]) {
                [_searchArr addObject:_searchBar.text];
                [Utils SetSearchArr:_searchArr];
            }
        }else{
            [_searchArr addObject:_searchBar.text];
            [Utils SetSearchArr:_searchArr];
        }
        
    }
    LOGoodsViewController *goods = [[LOGoodsViewController alloc] init];
    goods.searchGoodsName = _searchBar.text;
    goods.searchType = @"search";
    [self.navigationController pushViewController:goods animated:YES];
}

- (void)createLabelView
{
    [self.view addSubview:({
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 100, 20)];
        label.text = @"历史搜索";
        label.textColor = RGB(86, 86, 86);
        label.font = [UIFont systemFontOfSize:14.0];
        label;
    })];
    
    [self.view addSubview:({
        UIImageView *deleImg = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH-35, 150, 20, 20)];
        [deleImg setImage:[UIImage imageNamed:@"LOSearchDele"]];
        deleImg;
    })];
    
    [self.view addSubview:({
        UIButton *deleBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        deleBtn.frame = CGRectMake(WIDTH-45, 140, 40, 40);
        [deleBtn addTarget:self action:@selector(deleClick) forControlEvents:UIControlEventTouchUpInside];
        deleBtn;
    })];
    
    [self.view addSubview:({
        _labelView = [[selectLabelView alloc] initWithFrame:CGRectMake(0, 190, WIDTH, HEIGHT-120)];
        _labelView;
    })];
    
    __weak __typeof(self)weakSelf = self;
    _labelView.searchBtnclick = ^(NSString * searchText) {
        LOGoodsViewController *goods = [[LOGoodsViewController alloc] init];
        goods.searchGoodsName = searchText;
        goods.searchType = @"search";
        [weakSelf.navigationController pushViewController:goods animated:YES];
    };
}

- (void)deleClick
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"删除所有搜索记录" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            break;
        }
        case 1:
        {
            if ([Utils getUserToken]) {
                [self.view loadingOnAnyView];
                [THWManager PostHttp:API(LOSearchDelete) Parameters:@{@"userToken":[Utils getUserToken]} Success:^(id responseObject) {
                    [self.view Message:responseObject[@"msg"]];
                    [_labelView reloadData:nil];
                    [self.view removeAnyView];
                } andFalse:^(NSError *error) {
                    [self.view removeAnyView];
                }];
            }else{
                [_searchArr removeAllObjects];
                [_labelView reloadData:_searchArr];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SearchArr"];
                [[NSUserDefaults standardUserDefaults]synchronize];
            }
        }
        default:
            break;
    }
}

- (void)downloadData
{
    [self.view loadingOnAnyView];
    [THWManager GetHttp:API(LOSearch) Parameters:@{@"userToken":[Utils getUserToken]} Success:^(id responseObject) {
        if ([responseObject[@"data"] isKindOfClass:[NSArray class]]) {
            _NetSearchArr = responseObject[@"data"];
            [_labelView reloadData:_NetSearchArr];
        }
        [self.view removeAnyView];
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [_searchBar becomeFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
